package org.shock.ss.sms.service.system.impl;

import org.apache.commons.beanutils.BeanUtils;

import org.shock.ss.sms.commons.db.TsDbTools;
import org.shock.ss.sms.commons.db.ProxoolDbPool;

import org.shock.ss.sms.bean.system.Role;
import org.shock.ss.sms.bean.system.User;

import org.shock.ss.sms.commons.dao.BaseDao;
import org.shock.ss.sms.commons.service.impl.BaseServiceImpl;
import org.shock.ss.sms.service.system.RoleService;

public class RoleServiceImpl extends BaseServiceImpl implements RoleService {

	public RoleServiceImpl(BaseDao dao) {
		super(dao);
	}

	/** 保存角色权利 */
	public void saveRoleRights(Role role) throws Exception {
		try {
			tx = ProxoolDbPool.getTranManager();
			tx.beginTransaction();
			Role r = new Role();
			r.setId(role.getId());
			r.setRightids(role.getRightids());
			dao.update(r);
			tx.commitAndClose();
		} catch (Exception e) {
			if (tx != null)
				tx.rollbackAndClose();
			log.error(e, e);
			throw e;
		}
	}

	/** 保存角色拥有的用户 */
	public void saveRoleUsers(Long roleid, String userids, String ids)
			throws Exception {
		try {
			tx = ProxoolDbPool.getTranManager();
			tx.beginTransaction();
			//将选择到的用户添加该角色
			String sql = "update "+User.getTable()+" set roleids=ifnull(roleids,'-1')||',"
					+ roleid + "' where id in (" + userids
					+ ") and ','||roleids||',' not like '%," + roleid + ",%'";
			//未选择到的用户排除该角色
			String sql2 =" update "+User.getTable()+" set roleids=substr(replace(','||roleids||',',',"
					+ roleid
					+ ",',','),2,length(replace(','||roleids||',',',"
					+ roleid + ",',','))-2) where id in(" + ids + ")";
			TsDbTools.doSql(sql);
			TsDbTools.doSql(sql2);
			tx.commitAndClose();
		} catch (Exception e) {
			if (tx != null)
				tx.rollbackAndClose();
			log.error(e, e);
			throw e;
		}
	}
	/** 保存角色拥有的桌面portal */
	public void saveRolePortals(Role role) throws Exception {
		try {
			tx = ProxoolDbPool.getTranManager();
			tx.beginTransaction();
			Role r = new Role();
			r.setId(role.getId());
			r.setPortalids(role.getPortalids());
			dao.update(r);
			tx.commitAndClose();
		} catch (Exception e) {
			if (tx != null)
				tx.rollbackAndClose();
			log.error(e, e);
			throw e;
		}
		
	}
	/** 保存角色拥有的区域权限*/
	public void saveRoleArea(Role role) throws Exception {
		try {
			tx = ProxoolDbPool.getTranManager();
			tx.beginTransaction();
			Role r = new Role();
			r.setId(role.getId());
			r.setAreacodes(role.getAreacodes());
			dao.update(r);
			tx.commitAndClose();
		} catch (Exception e) {
			if (tx != null)
				tx.rollbackAndClose();
			log.error(e, e);
			throw e;
		}
	}
}
